<template>
  <view class="w-full">
    <van-panel>
      <view class="flex items-center c-pd pb-1 c-br" slot="header">
        <view class="flex-1">上传视频</view>
        <view class="flex-1 text-align-end">
          <van-button type="primary" plain size="mini" @click="clearVideoUrl">清空</van-button>
        </view>
      </view>
      <view class="c-pd pt-1">
        <van-uploader :disabled="data.tempPath ? true : false" :media-type="['video']" capture="media" accept="video" :max-count="1" @after-read="handleChooseImg($event)">
          <view class="h-full" :style="{ width: data.uploadWidth + 'px' }">
            <view v-if="!data.tempPath" class="upload-class">
              <i class="i-material-symbols-light:hangout-video-rounded w-20 h-20 c-color"></i>
              <view class="c-text-14">点击添加视频</view>
            </view>
            <video v-else show-play-btn class="img-size" :src="data.tempPath" />
          </view>
        </van-uploader>
      </view>
    </van-panel>
  </view>
</template>

<script setup lang="ts">
import Tools from '@/utils/tools';

interface IData {
  baseCode: string;
  tempPath: string;
  uploadWidth: number;
}

type EmitEvents = {
  (event: 'returnUrl', payload: { url: string }): void; //返回地址
  (event: 'clearUrl', payload: { url: string }): void; //清空地址
};

onLoad(() => {
  uni.getSystemInfo({
    success: (res) => {
      data.uploadWidth = res.windowWidth - 48;
    },
  });
});

const emits = defineEmits<EmitEvents>();

const data = reactive<IData>({
  baseCode: '',
  tempPath: '',
  uploadWidth: 0,
});

const handleChooseImg = async (event: any) => {
  data.baseCode = await Tools.uniBase64FromFile(event.detail.file.url);
  data.tempPath = event.detail.file.url;
  emits('returnUrl', { url: data.baseCode });
};

const clearVideoUrl = () => {
  data.baseCode = '';
  data.tempPath = '';
  emits('clearUrl', { url: data.baseCode });
};
</script>

<style lang="scss" scoped>
.img-size {
  width: 100%;
  height: 300rpx;
}

.upload-class {
  padding: 46rpx 0;
  width: 100%;
  height: 300rpx;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 16rpx;
  box-sizing: border-box;
}
</style>
